package com.jstyle.beatecg.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;

import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceListener;
import com.amap.api.trace.TraceLocation;
import com.amap.api.trace.TraceStatusListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.daoManager.PathRecordDaoManager;
import com.jstyle.beatecg.model.Gps;
import com.jstyle.beatecg.model.Mylocation;
import com.jstyle.beatecg.model.PathRecord;
import com.jstyle.beatecg.util.DateUtil;
import com.jstyle.beatecg.util.LanguageHelp;
import com.jstyle.beatecg.util.SharePreferenceUtils;
import com.jstyle.beatecg.util.Util;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TrackFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TrackFragment extends Fragment implements LocationSource, AMapLocationListener,OnMapReadyCallback {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.mapTrack)
    MapView mapTrack;
    Unbinder unbinder;
    @BindView(R.id.Chronometer_track)
    TextView ChronometerTrack;
    @BindView(R.id.tv_heart_data)
    TextView tvHeartData;
    @BindView(R.id.tv_step_data)
    TextView tvStepData;
    @BindView(R.id.tv_distance_data)
    TextView tvDistanceData;
    @BindView(R.id.tv_cal_data)
    TextView tvCalData;
    @BindView(R.id.shoewmapll)
    LinearLayout shoewmapll;

    MapFragment fragmentgoogle;//Google地图控件
    GoogleMap mygoogleMap;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    private AMap mAMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    PathRecord pathRecord;
    OnFragmentInteractionListener onFragmentInteractionListener;
    long mStartTime;
    long mEndTime;
    private PolylineOptions mPolyoptions;
    private List<com.google.android.gms.maps.model.LatLng> mPolyoptionsLatLng;
    private Polyline mpolyline;
    Mylocation amyMapLocation=new Mylocation();
    Boolean isChina=true;
    static String Type;
    LBSTraceClient lbsTraceClien;//偏纠
    int coubnt=0;
    public TrackFragment() {

    }
    public static void settype(String tYPE) {
       Type=tYPE;
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TrackFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TrackFragment newInstance() {
        TrackFragment fragment = new TrackFragment();
//        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
//        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_track, container, false);
        fragmentgoogle= (MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.qixinggoogle_map); /*** google地图控件*/
        unbinder = ButterKnife.bind(this, view);
        mapTrack.onCreate(savedInstanceState);
        initView();
        initpolyline();
        mPolyoptionsLatLng=new ArrayList<>();
        mStartTime = System.currentTimeMillis();
        pathRecord = new PathRecord();
        pathRecord.setMDate(DateUtil.getFormatTimeString(new Date().getTime()));
        if(null!=MyApplication.aMapLocation){
            amyMapLocation.setmAltitude(MyApplication.aMapLocation.getAltitude());
            amyMapLocation.setmLongitude(MyApplication.aMapLocation.getLongitude());
        }else if(null!=Util.getNetWorkLocation(getActivity())){
            amyMapLocation.setmAltitude(Util.gps84_To_Gcj02(Util.getNetWorkLocation(getActivity()).getAltitude(),Util.getNetWorkLocation(getActivity()).getLongitude()).getWgLat());
            amyMapLocation.setmLongitude(Util.gps84_To_Gcj02(Util.getNetWorkLocation(getActivity()).getAltitude(),Util.getNetWorkLocation(getActivity()).getLongitude()).getWgLon());
        }
            if(Util.outOfChina(amyMapLocation.getmAltitude(),amyMapLocation.getmLongitude())){
                mapTrack.setVisibility(View.VISIBLE);
                fragmentgoogle.getView().setSystemUiVisibility(View.GONE);
                isChina=true;
                lbsTraceClien = LBSTraceClient.getInstance(getActivity());
                coubnt=0;
            }else{
                isChina=false;
                mapTrack.setVisibility(View.GONE);
                fragmentgoogle.getView().setSystemUiVisibility(View.VISIBLE);
                fragmentgoogle.getMapAsync(this);//Google地图初始化
            }



        if("0".equals(SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_map))){
            Viewstatus(0);
        }else{
            Viewstatus(1);
        }

        return view;
    }
  /*  *//**
     * 是否支持google服务
     * @return
     *//*
    public boolean isServicesOK(){
        int available =GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getActivity());
        if(available == ConnectionResult.SUCCESS){ return true; } if(
                GoogleApiAvailability.getInstance().isUserResolvableError(available)
                ){
            android.app.Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), available, 2404);
            dialog.show(); }else{
        } return false;
    }*/


    private void initpolyline() {
        mPolyoptions = new PolylineOptions();
        mPolyoptions.width(15f);
        mPolyoptions.color(Color.GRAY);
    }


    private void initView() {
        if (mAMap == null) {
            mAMap = mapTrack.getMap();
            setUpMap();
        }
    }

    public void updateActivityData(float cal, int distance) {

        tvCalData.setText(cal + "");
        tvDistanceData.setText(distance + "");
    }
    List<Float> speedList=new ArrayList<>();
    List<Float>heartList=new ArrayList<>();
    float heart;
    public  void updateSpeed(float speed){
        NumberFormat numberFormat=NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(1);
        tvStepData.setText(numberFormat.format(speed));
        speedList.add(speed*5f+76);
        heartList.add(heart);
    }

    public  void updateHeartRate(String heartRate){
        tvHeartData.setText(heartRate);
        heart=Float.valueOf(heartRate);

    }
    // 自定义系统定位蓝点
  MyLocationStyle myLocationStyle = new MyLocationStyle();
    private void setUpMap() {
        mAMap.setLocationSource(this);// 设置定位监听
       //  mAMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        mAMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);


      /*  // 自定义定位蓝点图标+
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.location_marker));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(Color.TRANSPARENT);
        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
        // 自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(0);
        // 将自定义的 myLocationStyle 对象添加到地图上
        mAMap.setMyLocationStyle(myLocationStyle);
        mAMap.setLocationSource(this);// 设置定位监听
        mAMap.getUiSettings().setZoomControlsEnabled(false);//取消控制+ -
        mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        mAMap.getUiSettings().setMyLocationButtonEnabled(false);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);*///连续定位、且将视角移动到地图中心点，定位蓝点跟随设备移动
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {

    }

    public void updateTime(String time) {
        ChronometerTrack.setText(time);
    }

    public void stop() {
        mEndTime = System.currentTimeMillis();
        saveRecord(pathRecord.getmPathLinePoints(), pathRecord.getMDate());
        getActivity().finish();
    }

    private String getListString(List<Float>list){
        if (list == null || list.size() == 0) {
            return "";
        }
        StringBuffer pathline = new StringBuffer();
        for(float value:list){
            pathline.append(String.valueOf(value)).append(",");
        }
        String pathLineString = pathline.toString();
        pathLineString = pathLineString.substring(0,
                pathLineString.length() - 1);
        return pathLineString;
    }

    private static final String TAG = "TrackFragment";
    protected void saveRecord(List<AMapLocation> list, String time) {
        if (list != null && list.size() > 0) {
            String duration = getDuration();
            float distance = getDistance(list);
            String average = getAverage(distance);
            String pathlineSring = getPathLineString(list);
            AMapLocation firstLocaiton = list.get(0);
            AMapLocation lastLocaiton = list.get(list.size() - 1);
            String stratpoint = amapLocationToString(firstLocaiton);
            String endpoint = amapLocationToString(lastLocaiton);
            String cal=tvCalData.getText().toString();
            String distanceBeat=tvDistanceData.getText().toString();
            String heartString=getListString(heartList);
            Log.i(TAG, "saveRecord: "+heartString);
            String speedString=getListString(speedList);
            Log.i(TAG, "saveRecord: "+speedString);
            pathRecord.setHeartListString(heartString);
            pathRecord.setSpeedListString(speedString);
            pathRecord.setDistanceBeat(distanceBeat);
            pathRecord.setCalString(cal);
            pathRecord.setMDistance(String.valueOf(distance));
            pathRecord.setMAveragespeed(average);
            pathRecord.setPathline(pathlineSring);
            pathRecord.setStratpoint(stratpoint);
            pathRecord.setEndpoint(endpoint);
            pathRecord.setMDuration(duration);
            pathRecord.setType(Type);
            PathRecordDaoManager.insertPathRecord(pathRecord);
        } else {
         /*   Toast.makeText(getActivity(), "没有记录到路径", Toast.LENGTH_SHORT)
                    .show();*/
        }
    }

    private String getDuration() {
        return String.valueOf((mEndTime - mStartTime) / 1000f);
    }

    private String getAverage(float distance) {
        return String.valueOf(distance / (float) (mEndTime - mStartTime));
    }

    private float getDistance(List<AMapLocation> list) {
        float distance = 0;
        if (list == null || list.size() == 0) {
            return distance;
        }
        for (int i = 0; i < list.size() - 1; i++) {
            AMapLocation firstpoint = list.get(i);
            AMapLocation secondpoint = list.get(i + 1);
            LatLng firstLatLng = new LatLng(firstpoint.getLatitude(),
                    firstpoint.getLongitude());
            LatLng secondLatLng = new LatLng(secondpoint.getLatitude(),
                    secondpoint.getLongitude());
            double betweenDis = AMapUtils.calculateLineDistance(firstLatLng,
                    secondLatLng);
            distance = (float) (distance + betweenDis);
        }
        return distance;
    }

    private String getPathLineString(List<AMapLocation> list) {
        if (list == null || list.size() == 0) {
            return "";
        }
        StringBuffer pathline = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            AMapLocation location = list.get(i);
            String locString = amapLocationToString(location);
            pathline.append(locString).append(";");
        }
        String pathLineString = pathline.toString();
        pathLineString = pathLineString.substring(0,
                pathLineString.length() - 1);
        return pathLineString;
    }

    private String amapLocationToString(AMapLocation location) {
        StringBuffer locString = new StringBuffer();
        locString.append(location.getLatitude()).append(",");
        locString.append(location.getLongitude()).append(",");
        locString.append(location.getProvider()).append(",");
        locString.append(location.getTime()).append(",");
        locString.append(location.getSpeed()).append(",");
        locString.append(location.getBearing());
        return locString.toString();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onResume() {
        super.onResume();
        mapTrack.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //mapTrack.onPause();//不能加这句，定位异常情况下会导致app无法运行
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mapTrack.onDestroy();
        unbinder.unbind();
        if(isChina){
        lbsTraceClien.stopTrace();
        lbsTraceClien.destroy();}
    }

    private void startlocation() {
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(getActivity());
            mLocationOption = new AMapLocationClientOption();
            if(LanguageHelp.isEnglish()){
                mLocationOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.EN);
            }else{
                mLocationOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.ZH);
            }
            mLocationOption.setOnceLocation(false);
            // 设置定位监听
            mLocationClient.setLocationListener(this);
            mLocationOption.setWifiActiveScan(true);
            // 设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(4000);
            // 设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.startLocation();
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        startlocation();
    }

    public void Viewstatus(int type){
        if(null!=shoewmapll){
            if(0==type){
                shoewmapll.setVisibility(View.VISIBLE);
            }else{
                shoewmapll.setVisibility(View.GONE);
            }
        }

    }
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();

        }
        mLocationClient = null;
        isZoom=false;
    }

    boolean isZoom=false;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                if (aMapLocation.getLocationType() == 6 || aMapLocation.getAccuracy() >= 300)
                    return;
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                 LatLng mylocation = new LatLng(aMapLocation.getLatitude(),
                        aMapLocation.getLongitude());
                    if(isChina){
                       // Log.e("TrackFragment","wwwisChinaok"+aMapLocation.getLatitude()+"");
                        if (!isZoom) {
                            isZoom = true;
                            mAMap.moveCamera(CameraUpdateFactory.zoomTo(16f));
                            mPolyoptions.add(mylocation);
                            pathRecord.addPoint(aMapLocation);
                        }else{

                            int GpsAccuracyStatus = aMapLocation.getGpsAccuracyStatus();

                            LatLng oldlocation = new LatLng(pathRecord.getmPathLinePoints().get(pathRecord.getmPathLinePoints().size()-1).getLatitude(),
                                    pathRecord.getmPathLinePoints().get(pathRecord.getmPathLinePoints().size()-1).getLongitude());
                            double betweenDis = AMapUtils.calculateLineDistance(oldlocation, mylocation);
                          //  if (GpsAccuracyStatus == AMapLocation.GPS_ACCURACY_GOOD ) {


                            //0.0为原位置，超过5米才记录数据，速度大于1，否则认为静止状态
                            if((0.0!=betweenDis&&betweenDis>5)||aMapLocation.getSpeed()>1){
                                Log.e("destans",aMapLocation.toString()+"ok");
                                //Toast.makeText(getActivity(),aMapLocation.toString(),Toast.LENGTH_SHORT).show();
                                pathRecord.addPoint(aMapLocation);
                                 mPolyoptions.add(mylocation);
                                mAMap.animateCamera(CameraUpdateFactory.changeLatLng(mylocation));
                                redrawline();
                            }

                         /*  }else{
                                Log.e("destans",aMapLocation.getSpeed()+"no");
                               // Toast.makeText(getActivity(),betweenDis+"sadsdabuhao",Toast.LENGTH_SHORT).show();
                            }*/

                        }




                    }else{
                        pathRecord.addPoint(aMapLocation);
                        com.google.android.gms.maps.model.LatLng mylocationb = new com.google.android.gms.maps.model.LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                        com.google.android.gms.maps.model.LatLng sydney = new com.google.android.gms.maps.model.LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                        mygoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdateFactory.newLatLngZoom(sydney, 16));
                        mygoogleMap.addCircle(new CircleOptions().strokeWidth(1).strokeColor(Color.BLUE).fillColor(Color.GRAY).center(mylocationb));
                        mPolyoptionsLatLng.add(mylocationb);
                        if(mPolyoptionsLatLng.size()>1){
                            mygoogleMap.addCircle(new CircleOptions().strokeWidth(1).strokeColor(Color.BLUE).fillColor(Color.GRAY).center(mPolyoptionsLatLng.get(mPolyoptionsLatLng.size()-2)).visible(false));
                            mygoogleMap.addPolyline(new com.google.android.gms.maps.model.PolylineOptions().add(mPolyoptionsLatLng.get(mPolyoptionsLatLng.size()-2),mPolyoptionsLatLng.get(mPolyoptionsLatLng.size()-1)).width(10)
                                    .color(Color.BLUE).geodesic(true));
                        }
                    }





            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": "
                        + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapTrack.onSaveInstanceState(outState);
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mygoogleMap=googleMap;

        LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度，如果设置为高精度，依然获取不了location。
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(false);//允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
        //getBestProvider 只有允许访问调用活动的位置供应商将被返回
        String providerName = lm.getBestProvider(criteria, true);
      /*  if (providerName != null) {
            Location location = lm.getLastKnownLocation(providerName);
            if (location != null) {
                //获取维度信息
                double latitude = location.getLatitude();
                //获取经度信息
                double longitude = location.getLongitude();
                com.google.android.gms.maps.model.LatLng sydney = new com.google.android.gms.maps.model.LatLng(latitude, longitude);
                googleMap.setMyLocationEnabled(false);
                googleMap.moveCamera(com.google.android.gms.maps.CameraUpdateFactory.newLatLngZoom(sydney, 16));
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,null);
            }}*/
    }

/*    LocationListener locationListenerb = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Log.e("TrackFragment",location.getLatitude()+"");
            com.google.android.gms.maps.model.LatLng mylocation = new com.google.android.gms.maps.model.LatLng(location.getLatitude(), location.getLongitude());
            com.google.android.gms.maps.model.LatLng sydney = new com.google.android.gms.maps.model.LatLng(location.getLatitude(), location.getLongitude());
            mygoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdateFactory.newLatLngZoom(sydney, 16));

            mPolyoptionsLatLng.add(mylocation);
            if(mPolyoptionsLatLng.size()>1){
                mygoogleMap.addPolyline(new com.google.android.gms.maps.model.PolylineOptions().add(mPolyoptionsLatLng.get(mPolyoptionsLatLng.size()-2),mPolyoptionsLatLng.get(mPolyoptionsLatLng.size()-1)).width(10)
                        .color(Color.BLUE).geodesic(true));
            }
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) { }
        @Override
        public void onProviderEnabled(String provider) { }
        @Override
        public void onProviderDisabled(String provider) { }


    };*/

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void redrawline() {
        if (mPolyoptions.getPoints().size() > 1) {
            if (mpolyline != null) {
                mpolyline.setPoints(mPolyoptions.getPoints());
            } else {
                mpolyline = mAMap.addPolyline(mPolyoptions.setCustomTexture
                        (BitmapDescriptorFactory.fromResource(R.drawable.mapline)));
            }
        }
    }



}
